<template>
  <div class="postman">
    <div class="postman_hearer">
      <el-form class="demo-form-inline" :inline="true" :model="requestObj">
        <el-form-item label="">
          <el-select v-model="requestObj.way" size="mini">
            <!-- <el-option label="GET" value="get" /> -->
            <el-option label="POST" value="post" />
          </el-select>
        </el-form-item>
        <el-form-item label="" size="mini">
          <el-input v-model="requestObj.url" placeholder="请输入URL" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSend">SEND</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="postman_body">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="请求头" name="headers">
          <vxe-table ref="requestHead" border :data="tableData" :edit-config="{ trigger: 'click', mode: 'cell' }" height="200" show-overflow>
            <vxe-column type="checkbox" width="60" />
            <vxe-column :edit-render="{ autofocus: '.el-input__inner' }" field="key" title="Key">
              <template #edit="{ row }">
                <el-input v-model="row.key" :disabled="row.key === 'Content-Type'" size="mini" @change="inputChange(row)" />
              </template>
            </vxe-column>
            <vxe-column :edit-render="{ autofocus: '.el-input__inner' }" field="value" title="Value">
              <template #default="{ row }">
                <el-select v-if="row.key === 'Content-Type'" v-model="row.value" size="mini" @change="typeChang">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-input v-else v-model="row.value" size="mini" @change="inputChange(row)" />
              </template>
              <template #edit="{ row }">
                <el-select v-if="row.key === 'Content-Type'" v-model="row.value" size="mini" @change="typeChang">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-input v-else v-model="row.value" size="mini" @change="inputChange(row)" />
              </template>
            </vxe-column>
            <vxe-column field="" title="操作" width="100">
              <template #default="{ row }">
                <el-button v-if="row.key !== 'Content-Type' && (row.key || row.value)" style="color: #f56c6c" type="text" @click="deleRow(row)">
                  <vui-icon icon="delete-bin-line" />
                </el-button>
              </template>
            </vxe-column>
          </vxe-table>
        </el-tab-pane>
        <el-tab-pane label="请求参数" name="parameter">
          <CodeEditor
            v-model="requestData"
            :cm-options="{
              tabSize: 1,
              smartIndent: true,
              indetUnit: 1,
              styleActiveLine: true,
              lineNumbers: true,
              line: true,
              mode: 'application/json',
              theme: 'dracula',
              foldGutter: true,
              lineWrapping: true,
              autoRefresh: true,
            }"
            :height="200"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="postman_response">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1" title="Response">
          <div :style="{ height: `${Number(getHeight)}px` }">
            <CodeEditor
              v-model="responseData"
              :cm-options="{
                tabSize: 1,
                smartIndent: true,
                indetUnit: 1,
                styleActiveLine: true,
                lineNumbers: true,
                line: true,
                mode: 'application/json',
                viewportMargin: Infinity,
                theme: 'dracula',
                foldGutter: true,
                lineWrapping: true,
                autoRefresh: true,
              }"
              :height="true"
            />
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>
<script>
  import CodeEditor from '@dams/components/codeEditor.vue'
  import axios from 'axios'
  import debounce from 'lodash/debounce'
  export default {
    name: 'PostManDialog',
    components: { CodeEditor },
    props: {
      apiurl: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        clientHeight: 0,
        activeNames: ['1'],
        requestObj: {
          way: 'post',
          url: '',
        },
        requestData: '',
        activeName: 'headers',
        tableData: [
          { key: 'Content-Type', value: 'application/json;charset=utf-8' },
          { key: '', value: '' },
        ],
        responseData: '',
        options: [
          { value: 'application/json;charset=utf-8', label: 'application/json;charset=utf-8' },
          { value: 'application/x-www-form-urlencoded', label: 'application/x-www-form-urlencoded' },
          { value: 'application/xml', label: 'application/xml' },
          { value: 'text/xml', label: 'text/xml' },
        ],
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 450}`
      },
    },
    mounted() {
      // this.$refs.requestHead.setAllCheckboxRow(true)
      console.log(this.apiurl)
      this.windowResize()
      this.requestObj.url = this.apiurl
    },
    methods: {
      typeChang(val) {
        console.log(val)
      },
      windowResize: debounce(function () {
        console.log('windowResize', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      removeEscape(val) {
        const newVal = val.replace(/\n/g, '').replace(/\t/g, '')
        return newVal.substr(0, newVal.length - 1)
      },
      onSend() {
        if (!this.requestObj.url) return this.$message({ type: 'error', message: '请输入URL' })
        let tableFull = this.$refs.requestHead.getCheckboxRecords()
        if (this.$refs.requestHead.getCheckboxRecords().length === 0) {
          tableFull = [this.tableData[0]]
        }
        const headerData = {}
        tableFull.forEach((r) => {
          headerData[r.key] = r.value
        })
        let submit
        try {
          if (headerData['Content-Type'] === 'application/x-www-form-urlencoded') {
            //form参数单独处理
            const params = new URLSearchParams()
            submit = JSON.parse(this.requestData)
            for (const key in submit) {
              if (key === 'data') {
                submit[key] = JSON.stringify(submit[key])
              }
              params.append(key, submit[key])
            }
            submit = params
          } else {
            submit = this.requestData
          }
        } catch (error) {
          console.log(error)
          return this.$message({ type: 'error', message: '请输入JSON数据' })
        }
        axios({
          method: this.requestObj.way,
          url: this.requestObj.url,
          headers: headerData,
          data: submit,
          validateStatus: function (status) {
            return status < 500 // 处理状态码小于500的情况
          },
        })
          .then((r) => {
            console.log(r)
            this.responseData = JSON.stringify(r.data, null, 4)
          })
          .catch((e) => {
            this.responseData = JSON.stringify(e.data, null, 4)
          })
      },
      handleClick() {},
      async inputChange(val) {
        if (val.key && val.value) return
        this.$refs.requestHead.setAllCheckboxRow(true)
        this.$refs.requestHead.insertAt(
          {
            key: '',
            value: '',
          },
          -1
        )
      },
      deleRow(row) {
        this.$refs.requestHead.remove(row)
      },
    },
  }
</script>
<style lang="scss" scoped>
  // .postman_hearer {
  :deep() {
    .postman_hearer {
      .demo-form-inline {
        display: flex;
        .el-form-item {
          width: auto;
          .el-input .el-input__inner {
            width: 300px;
          }
          .el-select .el-input .el-input__inner {
            width: auto;
          }
        }
      }
    }
    .postman_body {
      .el-tabs__nav-wrap::after {
        height: 0;
      }
    }
  }
  // }
</style>
